package edu.zzuli.assistant.api.action;

import java.util.List;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import edu.zzuli.assistant.bean.Collect;
import edu.zzuli.assistant.bean.News;
import edu.zzuli.assistant.bean.User;
import edu.zzuli.assistant.service.CollectService;
import edu.zzuli.assistant.service.impl.CollectServiceImpl;
import edu.zzuli.assistant.until.StrUtil;

public class CollectAction  extends ActionSupport implements SessionAware ,ModelDriven{
	
	private CollectService collectService=new CollectServiceImpl();
	private Map<String, Object> session;
	private List<News> newsList;//收藏集合  
	private int page=1;//当前页数默认第一页
	private final int  PAGE_NUM = 10;
	private Collect collect;
	private String[] fieldUser = {"id","title","content","newsPics","postTime","authorName","user"};
	private String[] clazzFields =new String[] {"id","name","headUrl"};
	

	public Collect getCollect() {
		return collect;
	}

	public void setCollect(Collect collect) {
		this.collect = collect;
	}

	public Map<String, Object> getSession() {
		return session;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}
	
	public List<News> getNewsList() {
		return newsList;
	}
	
	public void setNewsList(List<News> newsList) {
		this.newsList = newsList;
	}

	@Override
	public Object getModel() {
		// TODO Auto-generated method stub
		if (collect!=null) {
			this.collect=new Collect();			
		}
		return collect;
	}
	// 搜收藏列表     collect_list.action

	public void list (){
		if (session.get("userId")!=null) {
			String userId = session.get("userId").toString();
			newsList=collectService.getCollectList(userId, page, PAGE_NUM);
			StrUtil.sendJson(News.class, fieldUser, User.class, clazzFields , newsList);
		}
		else{
			StrUtil.sendMsg(LOGIN);
		}
	} 
	
	// 添加收藏     collect_add.action 
	public void add (){		
			
		if (session.get("userId")!=null) {
			if(collect.getNews().getId()==null){
				
				StrUtil.sendMsg(ERROR);
			}
			else{
				collect.setUserId(session.get("userId").toString());
				boolean result=collectService.addCollect(collect);
				if (result) {
					StrUtil.sendMsg(SUCCESS);
				} else {
					StrUtil.sendMsg("fail");
				}
			}
		}
		else{
			StrUtil.sendMsg(LOGIN);
		}
	}
	   				
		
	// 取消收藏   collect_cancel.action 
	public void cancel (){
		if (session.get("userId")!=null) {
			if(collect.getNews().getId()==null){
				
				StrUtil.sendMsg(ERROR);
			}else{
				
				String userId = session.get("userId").toString();
				boolean result=collectService.deleteCollect(userId, collect.getNews().getId());
				if (result) {
					StrUtil.sendMsg(SUCCESS);
				} else {
					StrUtil.sendMsg("fail");
				}
			}
		}
		else{
			StrUtil.sendMsg(LOGIN);
		}
	
	}

}